package com.hhsjdesign.dynamicui.core.property.viewdata

import com.hhsjdesign.dynamicui.exception.ViewDeepOutMaxException
import com.hhsjdesign.dynamicui.core.widgetdata.WidgetData
import com.hhsjdesign.dynamicui.utils.ClassCachePool
import com.hhsjdesign.dynamicui.utils.DataCaller
import com.hhsjdesign.dynamicui.utils.ItemViewTypeConst
import org.json.JSONObject
import java.lang.reflect.Constructor
import kotlin.collections.ArrayList


/**
 * 解析视图树结构
 */
object ItemViewDataParser {

    /**
     * ViewGroup
     */
    private val layoutArray: List<String> = listOf(
        ItemViewData.ITEM_VIEW_TYPE_FRAME,
        ItemViewData.ITEM_VIEW_TYPE_LINEAR_V,
        ItemViewData.ITEM_VIEW_TYPE_LINEAR_H
    )

    fun parseItemViewDataByType(jo: JSONObject): ItemViewData? {
        val itemViewType = jo.optString("itemViewType", ItemViewTypeConst.LEFT_BIG_RIGHT_2_SMALL)
        val clazz = ClassCachePool.getClassByWidgetType(ClassCachePool.WIDGET_ITEM_DATA, itemViewType)
            ?: return null
        val constructor: Constructor<*> = clazz.getConstructor(String::class.java, JSONObject::class.java)
        return constructor.newInstance(itemViewType, jo) as? ItemViewData
    }

    /**
     * 解析出一个树状结构
     * @param cell 单个view的json
     * @param propertyJO 整个child的json
     * @param parentType 单个view的父布局类型
     * @param parentDeep 父布局的深度
     * @return 返回一个树状结构
     */
    @JvmStatic
    fun transform(
        cell: JSONObject?,
        propertyJO: JSONObject,
        parentType: String?,
        parentDeep: Int
    ): ItemViewData? {
        if (cell == null) {
            return null
        }
        if (parentDeep > 9) throw ViewDeepOutMaxException(parentDeep)
        val viewTree = ItemViewData()
        viewTree.parentType = parentType
        viewTree.name = cell.optString("name")
        viewTree.type = cell.optString("type")
        //父视图深度加1
        viewTree.deep = parentDeep + 1
        //很重要的一段，将参数属性解析到树结构中
        viewTree.injectProperty(propertyJO)
        if (layoutArray.contains(viewTree.type)) {
            val ja = cell.optJSONArray("list")
            if (ja != null && ja.length() > 0) {
                viewTree.treeList = ArrayList()
                for (i in 0 until ja.length()) {
                    transform(
                        ja.optJSONObject(i),
                        propertyJO,
                        viewTree.type,
                        viewTree.deep
                    )?.let {
                        viewTree.treeList?.add(it)
                    }

                }
            }
        }
        return viewTree
    }
}